package com.hsr.hotel.controller.user;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hsr.hotel.entity.User;
import com.hsr.hotel.entity.dto.Person;
import com.hsr.hotel.response.AjaxResult;
import com.hsr.hotel.response.MsgType;
import com.hsr.hotel.response.ResponseTool;
import com.hsr.hotel.service.UserService;
import com.hsr.hotel.utils.MD5Utils;
import com.hsr.hotel.utils.SendmailUtil;
import com.hsr.hotel.utils.VerifyCodeUtil;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static org.apache.commons.codec.binary.Base64.encodeBase64;

@RestController
@RequestMapping(value = "/user")
public class UserController {
    @Autowired
    private UserService userService;

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    private String filePath = "D:\\project\\hotel-manager\\src\\main\\resources\\img\\";

    @RequestMapping("/check")
    public AjaxResult fileUploads(HttpServletRequest request, @RequestParam("file") MultipartFile file) throws IOException {
        // 得到格式化后的日期
        String format = sdf.format(new Date());
        // 获取上传的文件名称
        String fileName = file.getOriginalFilename();
        // 时间 和 日期拼接
        String newFileName = format + "_" + fileName;
        // 得到文件保存的位置以及新文件名
        File dest = new File(filePath + newFileName);
        try {

            /**
             * 做扫描
             */
            //API产品路径
            String requestUrl = "https://personcard.market.alicloudapi.com/ai_market/ai_ocr_universal/shen_fen_zheng/ch/v1";
            //阿里云APPCODE
            String appcode = "1696421f906a469dbcecd0d31f4b9f30";
            CloseableHttpClient httpClient = null;
            Person person = null;
            try {
                httpClient = HttpClients.createDefault();
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                // 装填参数
                if (true) {
                    //启用BASE64编码方式进行识别
                    //内容数据类型是BASE64编码
                    String imgFile = filePath + newFileName;
                    String imgBase64 = "";
                    try {
                        File file1 = new File(imgFile);
                        byte[] content = new byte[(int) file1.length()];
                        FileInputStream finputstream = new FileInputStream(file1);
                        finputstream.read(content);
                        finputstream.close();
                        imgBase64 = new String(encodeBase64(content));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    params.add(new BasicNameValuePair("IMAGE", imgBase64));
                    params.add(new BasicNameValuePair("IMAGE_TYPE", "0"));
                } else {
                    //启用URL方式进行识别
                    //内容数据类型是图像文件URL链接
                    params.add(new BasicNameValuePair("IMAGE", "https://icredit-api-market.oss-cn-hangzhou.aliyuncs.com/%E8%BA%AB%E4%BB%BD%E8%AF%81_%E5%8F%8D%E9%9D%A2.jpg"));
                    params.add(new BasicNameValuePair("IMAGE_TYPE", "1"));
                }

                // 创建一个HttpPost实例
                HttpPost httpPost = new HttpPost(requestUrl);
                httpPost.addHeader("Authorization", "APPCODE " + appcode);
                httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

                // 设置请求参数
                httpPost.setEntity(new UrlEncodedFormEntity(params, "utf-8"));

                // 发送POST请求
                HttpResponse execute = httpClient.execute(httpPost);

                // 获取状态码
                int statusCode = execute.getStatusLine().getStatusCode();
                System.out.println(statusCode);

                // 获取结果
                HttpEntity entity = execute.getEntity();
                String result = EntityUtils.toString(entity, "utf-8");
                System.out.println(result);

                /**
                 * jsonString转实体类
                 */
                JSONObject jsonObject = JSON.parseObject(result);
                person = jsonObject.toJavaObject(Person.class);

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (httpClient != null) {
                    try {
                        httpClient.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }


            // 上传的文件被保存了
            file.transferTo(dest);
            // 打印日志
            // 自定义返回的统一的 JSON 格式的数据，可以直接返回这个字符串也是可以的。
            return ResponseTool.success(person.get身份证识别实体信息().get身份证人像面实体信息());
        } catch (IOException e) {
            System.out.println(e);
        }
        // 待完成 —— 文件类型校验工作
        return ResponseTool.success();
    }

    /**
     * 更新课户信息
     *
     * @param userId
     * @param name
     * @param gender
     * @param phone
     * @param email
     * @param address
     * @param idcard
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/update")
    public AjaxResult userUpdate(Integer userId, String name, String gender, String phone,
                                 String email, String address, String idcard, HttpServletRequest request) {
        HttpSession session = request.getSession();
        if (!session.getAttribute("userId").equals(userId)) {
            return ResponseTool.failed(MsgType.PERMISSION_DENIED);
        }
        User user = new User();
        user.setUserId(userId);
        user.setName(name);
        user.setGender(gender);
        user.setPhone(phone);
        user.setEmail(email);
        user.setAddress(address);
        user.setIdcard(idcard);
        if (userService.updateUser(user) == 1)
            return ResponseTool.success("修改成功");
        return ResponseTool.success("修改失败，请检查或稍后再试");
    }

    /**
     * 更改密码
     *
     * @param username
     * @param oldPassword
     * @param newPassword
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/updatePassword")
    public AjaxResult updatePassword(String username, String oldPassword, String newPassword) {
        User user = userService.selectByUsernameAndPassword(username, oldPassword);
        if (user == null) {
            return ResponseTool.failed("密码不对");
        }
        user.setPassword(newPassword);
        if (userService.updateUser(user) == 1)
            return ResponseTool.success("修改成功");
        return ResponseTool.failed("修改失败");
    }

    /**
     * 获取个人资料
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/profile")
    public AjaxResult getProfile(HttpServletRequest request) {
        String username = (String) request.getSession().getAttribute("username");
        User user = userService.selectByUsername(username);
        if (user == null) return ResponseTool.failed("未知错误");
        user.setPassword(null);
        StringBuilder sb = new StringBuilder(user.getIdcard());
        sb.replace(5, 12, "********");
        user.setIdcard(sb.toString());
        return ResponseTool.success(user);
    }


    @RequestMapping("/checkUserOremail")
    public AjaxResult checkUsernameAndEmail(HttpSession session, String username, String email) {

        User user = userService.selectByUsername(username);
        if (user == null)
            return ResponseTool.failed("用户不存在");

        if (user.getEmail().equals(email)) {
            try {
                String verifyCode = null;
                // 如果验证码等于空的话就通过邮箱发送
                verifyCode = VerifyCodeUtil.generateVerifyCode(6);
                String emailTitle = "【嘉丽酒店管理系统】邮箱验证";
                String emailContent = "您正在【嘉丽酒店管理系统】进行邮箱验证，您的验证码为：" + verifyCode + "，请于5分钟内完成验证！";
                SendmailUtil.sendEmail(email, emailTitle, emailContent);
                session.setMaxInactiveInterval(60);
                System.out.println(session.getId());
                session.setAttribute("code", verifyCode);

                return ResponseTool.success("请到邮箱获取验证码");
                // 如果不等于空的话就直接进行验证
            } catch (Exception e) {

               /* model.addAttribute("info", errorInfo);
                return "findPass";*/
            }
        }
        //返回邮箱或者用户名不存在
        return ResponseTool.failed("邮箱输入错误");
    }


    @RequestMapping("/checkCode")
    public AjaxResult checkCode(HttpSession session, String code, String username) {

        if (userService.selectByUsername(username) == null)
            return ResponseTool.failed("用户未登录");

        String vertifyCode = (String) session.getAttribute("code");
        if (code.equals(vertifyCode))
            return ResponseTool.success();
        return ResponseTool.failed("验证码错误");
    }

    /**
     * x修改密码
     *
     * @param session
     * @param password
     * @param
     * @return
     */
    @RequestMapping(value = "/resetPass", method = RequestMethod.POST)
    public AjaxResult resetPass(HttpSession session, String password, String username) {
        User user = userService.selectByUsername(username);
        if (user == null)
            return ResponseTool.failed("用户名不存在");
        //密码
        user.setPassword(MD5Utils.MD5Encode(password));
        userService.updateUser(user);

        session.removeAttribute("code");
        return ResponseTool.success();
    }

    /**
     * 注销
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public AjaxResult logout(HttpServletRequest request) {
        HttpSession session = request.getSession();
        if (session != null) {

            session.removeAttribute("userId");
            session.removeAttribute("username");

            return ResponseTool.success("注销成功");
        }
        return ResponseTool.failed("未登录");
    }


}
